package cn.chendd.transactional.service.impl;

import cn.chendd.bless.mapper.GoodLuckMapper;
import cn.chendd.bless.model.GoodLuck;
import cn.chendd.transactional.service.TransactionalService;
import cn.chendd.users.mapper.UsersMapper;
import cn.chendd.users.model.Users;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 验证事务接口实现
 *
 * @author chendd
 * @date 2023/1/20 16:29
 */
@Service
public class TransactionalServiceImpl implements TransactionalService {

    /**
     * 本机数据源
     */
    @Resource
    private UsersMapper usersMapper;
    /**
     * 远程数据源
     */
    @Resource
    private GoodLuckMapper goodLuckMapper;
    @Resource(name = "blessNamedParameterJdbcTemplate")
    private NamedParameterJdbcTemplate blessJdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData() {
        //构造用户数据对象并保存
        Users user = new Users(null , "chendd" , "男" , "88911006@qq.com" , LocalDateTime.now().toString());
        this.usersMapper.insert(user);
        //构造好运数据对象并保存
        GoodLuck goodLuck = new GoodLuck(null , "chendd" , "春节快乐！");
        this.goodLuckMapper.insert(goodLuck);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDataMyBatisPlus() {
        this.saveData();
        System.out.println("抛出异常，事务回滚...");
        throwException();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDataMyBatisPlusOrJdbcTemplate() {
        //构造用户数据对象并保存
        Users user = new Users(null , "chendd" , "男" , "88911006@qq.com" , LocalDateTime.now().toString());
        this.usersMapper.insert(user);
        //构造好运数据对象并保存
        GoodLuck goodLuck = new GoodLuck(IdWorker.getId(), "chendd" , "春节快乐！");
        String sql = "insert into test(id , name , remark) values (:id , :name , :remark)";
        this.blessJdbcTemplate.batchUpdate(sql , SqlParameterSourceUtils.createBatch(goodLuck));
        System.out.println("抛出异常，事务回滚...");
        throwException();
    }

    @Override
    public Users queryUsers() {
        return this.usersMapper.queryUsers();
    }

    /**
     * 抛出运行时异常
     */
    private void throwException() {
        System.out.println(1 / 0);
    }

}
